<template>
  <div class="real-time-location bg-background text-foreground p-4">
    <h2 class="mb-6 text-2xl font-bold">实时位置</h2>

    <div class="search-form bg-card text-card-foreground mb-6 rounded-lg p-6 shadow-md">

      <QueryForm :model="filters" :formItems="formItems" @search="searchaaa" @reset="resetFilters" />
    </div>

    <div
      class="action-buttons bg-card text-card-foreground mb-6 flex items-center justify-between rounded-lg p-4 shadow-md">
      <div class="flex space-x-2">
        <!-- <button @click="addNew" class="btn btn-primary">
          新增
        </button>
        <button @click="deleteSelected" class="btn btn-destructive">
          删除
        </button> -->
        <!-- <button @click="openImportDialog" class="btn btn-secondary">
          导入
        </button> -->
        <el-button @click="exportData">导出</el-button>
      </div>
    </div>

    <div class="data-table bg-card text-card-foreground overflow-hidden rounded-lg shadow-md">
      <div class="overflow-x-auto">
        <table class="divide-border min-w-full divide-y">
          <thead>
            <tr class="bg-muted">
              <th class="table-header w-[60px]">
                <input type="checkbox" :checked="selectAll" @change="toggleSelectAll" class="checkbox" />
              </th>
              <th v-for="header in tableHeaders" :key="header" class="table-header">
                {{ header }}
              </th>
              <!-- <th class="table-header">操作</th> -->
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in paginatedData" :key="item.id" class="hover:bg-muted/50">
              <td class="table-cell w-[60px]">
                <input type="checkbox" v-model="item.selected" class="checkbox" />
              </td>
              <td class="table-cell">{{ item.DEVICE_CODE }}</td>
              <td class="table-cell">{{ item.STAFF_CODE }}</td>
              <td class="table-cell">{{ item.LONGITUDE }}</td>
              <td class="table-cell">{{ item.LATITUDE }}</td>
              <td class="table-cell">{{ item.LOCATION }}</td>
              <!-- <td class="table-cell">
                <button @click="editItem(item)" class="btn btn-secondary btn-sm">
                  编辑
                </button>
              </td> -->
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="pagination bg-card text-card-foreground mt-4 flex items-center justify-between p-4">
      <div>
        <p class="text-sm">
          共 <span class="font-medium">{{ totalItems }}</span> 条
        </p>
      </div>
      <div>
        <nav class="relative z-0 inline-flex -space-x-px rounded-md shadow-sm" aria-label="Pagination">
          <button @click="prevPage" :disabled="currentPage === 1" class="btn-pagination">
            上一页
          </button>
          <button v-for="page in displayedPages" :key="page" @click="goToPage(page)" :class="[
            'btn-pagination',
            currentPage === page
              ? 'bg-primary text-primary-foreground'
              : 'bg-card text-card-foreground hover:bg-muted',
          ]">
            {{ page }}
          </button>
          <button @click="nextPage" :disabled="currentPage === totalPages" class="btn-pagination">
            下一页
          </button>
        </nav>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%" @close="closeDialog"
      class="bg-background text-foreground">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="定位终端编码" prop="routeCode">
          <el-input v-model="formData.routeCode" class="input"></el-input>
        </el-form-item>
        <el-form-item label="人员编码" prop="personnelCode">
          <el-input v-model="formData.personnelCode" class="input"></el-input>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="formData.longitude" class="input"></el-input>
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="formData.latitude" class="input"></el-input>
        </el-form-item>
        <el-form-item label="位置描述" prop="locationDescription">
          <el-input v-model="formData.locationDescription" class="input"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" class="btn btn-secondary">取 消</el-button>
          <el-button type="primary" @click="saveLocation" class="btn btn-primary">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <Teleport to="body">
      <div v-if="isImportDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-bold">导入实时位置数据</h3>
            <button @click="closeImportDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-4">
            <input type="file" @change="handleFileUpload" accept=".xlsx, .xls"
              class="text-muted-foreground file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold" />
          </div>

          <div class="flex justify-end space-x-2">
            <button @click="closeImportDialog" class="btn btn-secondary">
              取消
            </button>
            <button @click="importData" class="btn btn-primary">导入</button>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, computed, reactive, watch, onMounted, getCurrentInstance } from 'vue'
import { PlusIcon, TrashIcon, UploadIcon, DownloadIcon } from 'lucide-vue-next'
import { saveAs } from 'file-saver'
import * as XLSX from 'xlsx'
import axios from 'axios'
const { proxy } = getCurrentInstance()

const apiBaseUrl = ref(proxy.$currentUrl + '/api/personnel-realtime-location')
// import {
//   ElMessage,
//   ElDialog,
//   ElForm,
//   ElFormItem,
//   ElInput,
//   ElButton,
// } from 'element-plus'

const filters = ref({
  DEVICE_CODE: '',
  STAFF_CODE: '',
})
const formItems = ref([
  {
    label: '定位终端编码：',
    model: 'DEVICE_CODE',
    type: 'input',
    placeholder: '请输入',
  },

  {
    label: '人员编码：',
    model: 'STAFF_CODE',
    type: 'input',
    placeholder: '请输入',
  },


])
const tableHeaders = ['定位终端编码', '人员编码', '经度', '纬度', '位置描述']

const locationData = ref([])
const currentPage = ref(1)
const itemsPerPage = 10
const selectAll = ref(false)
const isEditing = ref(false)
const formData = ref({
  id: null,
  routeCode: '',
  personnelCode: '',
  longitude: '',
  latitude: '',
  locationDescription: '',
})

const totalItems = computed(() => locationData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / itemsPerPage))

const startIndex = computed(() => (currentPage.value - 1) * itemsPerPage)
const endIndex = computed(() =>
  Math.min(startIndex.value + itemsPerPage, totalItems.value),
)

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage
  const end = start + itemsPerPage
  return locationData.value.slice(start, end)
})

const displayedPages = computed(() => {
  const range = 2
  const pages = []
  for (
    let i = Math.max(1, currentPage.value - range);
    i <= Math.min(totalPages.value, currentPage.value + range);
    i++
  ) {
    pages.push(i)
  }
  return pages
})

const loadData = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: filters.value })
    locationData.value = response.data.map(equipment => ({ ...equipment, selected: false }))
  } catch (error) {
    alert('搜索失败')
  }

}
const searchaaa = () => {
  // 先重新加载所有数据
  loadData()
  // 然后根据条件过滤
  // locationData.value = locationData.value.filter((item) => {
  //   const routeCodeMatch =
  //     !filters.value.staffCode ||
  //     item.staffCode
  //       .toLowerCase()
  //       .includes(filters.value.staffCode.toLowerCase())
  //   const personnelCodeMatch =
  //     !filters.value.deviceCode ||
  //     item.deviceCode
  //       .toLowerCase()
  //       .includes(filters.value.deviceCode.toLowerCase())
  //   return routeCodeMatch && personnelCodeMatch
  // })
  // 重置页码
  currentPage.value = 1
}

const resetFilters = () => {
  filters.value = {
    DEVICE_CODE: '',
    STAFF_CODE: '',
  }
  // 重新加载所有数据
  loadData()
  // 重置页码
  currentPage.value = 1
}

const rules = reactive({
  routeCode: [
    { required: true, message: '请输入定位终端编码', trigger: 'blur' },
  ],
  personnelCode: [
    { required: true, message: '请输入人员编码', trigger: 'blur' },
  ],
  longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
  latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
  locationDescription: [
    { required: true, message: '请输入位置描述', trigger: 'blur' },
  ],
})

const formRef = ref(null)
const dialogVisible = ref(false)
const dialogTitle = computed(() =>
  isEditing.value ? '编辑位置信息' : '新增位置信息',
)

const addNew = () => {
  isEditing.value = false
  dialogVisible.value = true
  formData.value = {
    id: null,
    routeCode: '',
    personnelCode: '',
    longitude: '',
    latitude: '',
    locationDescription: '',
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const editItem = (item) => {
  isEditing.value = true
  dialogVisible.value = true
  formData.value = { ...item }
}

const saveLocation = () => {
  if (formRef.value) {
    formRef.value.validate((valid) => {
      if (valid) {
        if (isEditing.value) {
          const index = locationData.value.findIndex(
            (item) => item.id === formData.value.id,
          )
          if (index !== -1) {
            locationData.value[index] = { ...formData.value }
          }
        } else {
          locationData.value.push({
            id: locationData.value.length + 1,
            ...formData.value,
            selected: false,
          })
        }
        ElMessage.success(isEditing.value ? '编辑成功' : '新增成功')
        closeDialog()
      } else {
        ElMessage.error('请填写完整信息')
        return false
      }
    })
  }
}

const closeDialog = () => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const deleteSelected = () => {
  locationData.value = locationData.value.filter((item) => !item.selected)
  selectAll.value = false
}

const exportData = () => {
  // const dataToExport = locationData.value.map(
  //   ({ id, selected, ...rest }) => rest,
  // )
  const dataToExport = locationData.value.map((expert) => ({
    '定位终端编码': expert.DEVICE_CODE,
    '人员编码': expert.STAFF_CODE,
    '经度': expert.LONGITUDE,
    '纬度': expert.LATITUDE,
    '位置描述': expert.LOCATION,
  }))
  const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '实时位置数据')
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  const data = new Blob([excelBuffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  })
  saveAs(data, '实时位置数据.xlsx')
}

const isImportDialogOpen = ref(false)
const importFile = ref(null)

const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
}

const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}

const importData = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }

  const reader = new FileReader()
  reader.onload = async (e) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    const jsonData = XLSX.utils.sheet_to_json(worksheet)

    try {
      console.log('导入数据:', jsonData)
      // 这里添加实际的导入API调用
      // const response = await axios.post(`${apiBaseUrl}/import`, jsonData)
      // console.log('导入响应:', response.data)
      alert('数据导入成功')
      closeImportDialog()
      loadData() // 刷新数据
    } catch (error) {
      console.error('导入失败:', error)
      alert('导入失败：' + error.message)
    }
  }
  reader.readAsArrayBuffer(importFile.value)
}

const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
  locationData.value.forEach((item) => (item.selected = selectAll.value))
}

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}

const goToPage = (page) => {
  currentPage.value = page
}

// Initial data load

// 添加这些样式相关的计算属性
const btnClasses = computed(() => {
  return 'px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out'
})

const btnPrimaryClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-primary text-primary-foreground hover:bg-primary/90',
  ]
})

const btnSecondaryClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-secondary text-secondary-foreground hover:bg-secondary/80',
  ]
})

const btnDestructiveClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-destructive text-destructive-foreground hover:bg-destructive/90',
  ]
})

// 更新你的模板以使用这些计算属性作为按钮类

// 5. 添加监听器
watch(
  [filters],
  () => {
    console.log('搜索条件变化:', filters.value)
  },
  { deep: true },
)

// 6. 确保初始加载
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.input {
  @apply border-input bg-background focus:border-primary focus:ring-primary mt-1 block w-full rounded-md shadow-sm focus:ring focus:ring-opacity-50;
}

.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.checkbox {
  @apply text-primary focus:ring-primary border-input h-4 w-4 rounded;
}

.table-header {
  @apply px-6 py-3 text-left text-xs font-medium uppercase tracking-wider;
}

.table-cell {
  @apply whitespace-nowrap px-6 py-4 text-sm;
}

.btn-pagination {
  @apply border-border relative inline-flex items-center border px-4 py-2 text-sm font-medium;
}

/* 覆盖 Element Plus 的一些样式以匹配我们的主题 */
:deep(.el-dialog) {
  @apply bg-background text-foreground;
}

:deep(.el-dialog__header) {
  @apply bg-muted text-foreground;
}

:deep(.el-dialog__body) {
  @apply bg-background text-foreground;
}

:deep(.el-dialog__footer) {
  @apply bg-muted text-foreground;
}
</style>
